# -*- coding: utf-8 -*-
import urllib
import collections
from flask import json

__author__ = 'XiuGang-Ye'
__date__ = '2017/3/15 11:32'
import urllib2
import time
import hashlib
# http
HTTP_C_LE = '\x1B\x61\x31'  # 为居中
HTTP_C_RI = '\x1B\x61\x30'
HTTP_L_LE = '\x1C\x21\x78\x1B\x21\x50'  # 字体变高一倍
HTTP_L_RI = '\x1C\x21\x70\x1B\x21\x40'
HTTP_B_LE = '\x1C\x21\x7C\x1B\x21\x70'  # 大号字体
HTTP_B_RI = '\x1C\x21\x70\x1B\x21\x40'
HTTP_W_LE = '\x1C\x21\x74\x1B\x21\x60'  # 倍宽
HTTP_W_RI = '\x1C\x21\x70\x1B\x21\x40'
HTTP_LC_LE = '\x1C\x21\x78\x1B\x21\x50\x1B\x61\x31'  # 倍高居中
HTTP_LC_RI = '\x1C\x21\x70\x1B\x21\x40\x1B\x61\x30'
HTTP_WC_LE = '\x1C\x21\x74\x1B\x21\x60\x1B\x61\x31'  # 倍宽居中
HTTP_WC_RI = '\x1C\x21\x70\x1B\x21\x40\x1B\x61\x30'
HTTP_BC_LE = '\x1C\x21\x7C\x1B\x21\x70\x1B\x61\x31'  # 大号居中
HTTP_BC_RI = '\x1C\x21\x70\x1B\x21\x40\x1B\x61\x30'
HTTP_EA = '\x1B\x64\x02\x1B\x61\x31\x1D\x48\x32\x1D\x68\xA2\x1D\x6B\x43\x0C'  # 后面加上条形码的12位数字
HTTP_QR_LE = 'QRCODEBEGIN'  # 二维码 最大支持128个英文字符
HTTP_QR_RI = 'QRCODEEND'  # 只会在小票的末尾进行打印
HTTP_MSG_BEGIN = 'MESSAGEBEGIN'  # 表明正确信息的开头.带了他才可以打印
# yun
YUN_CB_LE = '<CB>'  # 为居中放大一倍
YUN_CB_RI = '</CB>'
YUN_B_LE = '<B>'  # 为放大一倍
YUN_B_RI = '</B>'
YUN_C_LE = '<C>'  # 为居中
YUN_C_RI = '</C>'
YUN_L_LE = '<L>'  # 字体变高一倍
YUN_L_RI = '</L>'
YUN_W_LE = '<W>'  # 字体变宽一倍
YUN_W_RI = '</W>'
YUN_QR_LE = '<QR>'  # 为二维码
YUN_QR_RI = '</QR>'
YUN_BOLD_LE = '<BOLD>'  # 为字体加粗
YUN_BOLD_RI = '</BOLD>'
YUN_RIGHT_LE = '<RIGHT>'  # 为右对齐
YUN_RIGHT_RI = '</RIGHT>'
YUN_CUT = '<CUT>'  # 为切刀指令(主动切纸,仅限切刀打印机使用才有效果)
YUN_BR = '<BR>'  # 为换行
YUN_PLUGIN = '<PLUGIN>'  # 为钱箱或者外置音响指令
YUN_LOGO = '<LOGO>'  # 为打印LOGO指令(前提是预先在机器内置LOGO图片)

# 说明：
URL = "http://api.feieyun.cn/Api/Open/"  # 不需要修改
STIME = str(int(time.time()))  # 不需要修改
USER = "2225759935@qq.com"  # *必填*：账号名
UKEY = "Ww5jt539bQSFMyc6"  # *必填*: 注册账号后生成的UKEY
SN = "916503858"  # *必填*：打印机编号，必须要在管理后台里添加打印机之后，才能调用API
# 916800415
# 功能代码
PRINTMSG = 'Open_printMsg'
PRINTINFO = 'Open_queryOrderInfoByDate'

# 小票长度
# MAXLENTH = 32


MAXLENTH = 48


# 打印格式
def formatMsg(aDict):
    newLine = '\n'
    buf = HTTP_MSG_BEGIN
    buf += addStyle('欢迎光临' + newLine + '肉菜通智慧菜市场' + newLine, HTTP_LC_LE, HTTP_LC_RI)
    buf += newLine + param_1('单号:', aDict['order'])
    buf += newLine + '*' * MAXLENTH
    buf += newLine + param_1('市场:', aDict['market'])
    buf += newLine + param_1('账号:', aDict['account'])
    buf += newLine + param_1('支付:', aDict['pay_t'])
    buf += newLine
    buf += newLine + param_1('时间:', aDict['dtime'])
    buf += newLine + '-' * MAXLENTH
    buf += newLine + param_5('名称', '重量', '皮重', '单价', '小计')
    for order in aDict['orders']:
        buf += newLine + param_5(order['name'], "%.2f" % order['weight'], "%.2f" % order['pi'], "%.2f" % order['price'],
                                 "%.2f" % order['total'])
    buf += newLine + '-' * MAXLENTH
    buf += newLine + param_2('数量(件):', aDict['count'])
    buf += newLine + param_2('重量(公斤):', aDict['weight'])
    buf += newLine + param_2('应付(元):', aDict['ypay'])
    buf += newLine + param_2('节省(元):', aDict['save'])
    buf += newLine + param_2('实付(元):', aDict['spay'])
    buf += newLine + '*' * MAXLENTH
    buf += newLine
    buf += newLine
    buf += newLine + addStyle('http://www.rctflat.com' + newLine + newLine + '400-888-888' + newLine, HTTP_C_LE,
                              HTTP_C_RI)

    buf = buf.decode('utf-8').encode('GB18030')
    print buf
    return buf
    # return yunprintOrder(buf)



def addHeader():
    pass


def addFooter():
    pass


# 增加 .样式
def addStyle(aWords, aStart, aEnd):
    msg = aStart + aWords + aEnd
    return msg


# 使用范围,如: 名称: 白菜 不需要分成两列
def param_1(aParam1, aParam2):
    msg = ''
    msg += str(aParam1) + getBlank(1) + str(aParam2)
    return msg


# 两列的小票
def param_2(aParam1, aParam2):
    msg = ''
    msg += str(aParam1) + getBlank(MAXLENTH - charLen(str(aParam1)) - charLen(str(aParam2))) \
           + str(aParam2)
    return msg


def param_3(aParam1, aParam2, aParam3):
    msg = ''
    msg += str(aParam1) + getBlank(MAXLENTH / 2 - charLen(str(aParam1)) - charLen(str(aParam2)) / 2) \
           + str(aParam2) + getBlank(MAXLENTH / 2 - charLen(str(aParam3)) - charLen(str(aParam2)) / 2) \
           + str(aParam3)
    return msg


'''
def param_4(aParam1, aParam2, aParam3, aParam4):
    msg = ''
    msg += str(aParam1) + getBlank(16 - charLen(str(aParam1))) \
           + str(aParam2) + getBlank(14 - charLen(str(aParam2))) \
           + str(aParam3) + getBlank(12 - charLen(str(aParam3))) \
           + str(aParam4)
    return msg
'''


def param_4(aParam1, aParam2, aParam3, aParam4):
    msg = ''
    msg += str(aParam1) + getBlank(MAXLENTH / 2 - charLen(str(aParam1)) - charLen(str(aParam2))) \
           + str(aParam2) + getBlank(MAXLENTH / 4 - charLen(str(aParam3))) \
           + str(aParam3) + getBlank(MAXLENTH / 4 - charLen(str(aParam4))) \
           + str(aParam4)
    return msg


def param_5(aParam1, aParam2, aParam3, aParam4, aParam5):
    msg = ''
    msg += str(aParam1) + getBlank(MAXLENTH / 2 - charLen(str(aParam1)) - charLen(str(aParam2)) - 3) \
           + str(aParam2) + getBlank(8 - charLen(str(aParam3)) + 1) \
           + str(aParam3) + getBlank(8 - charLen(str(aParam4)) + 1) \
           + str(aParam4) + getBlank(8 - charLen(str(aParam5)) + 1) \
           + str(aParam5)

    return msg


# 填充空格
def getBlank(count):
    buf = ''
    for a in range(int(count)):
        buf = buf + ' '
    return buf


# 计算长度,主要解决中文问题
# \uffe5 ==  ￥ 是货币符号,占两个位置
def charLen(aMsg):
    char_len = 0
    msg = aMsg.decode('utf-8')
    for ch in msg:
        if (ch >= u'\u4e00' and ch <= u'\u9fa5') or ch == u'\uffe5':
            char_len += 2
        else:
            char_len += 1
    return char_len


# 云打印
def yunprintOrder(aContent):
    params = addParams(PRINTMSG, aContent)
    recv_data = requestUrl(params)

    if recv_data is None:
        return ''

    tmpJson = json.loads(recv_data)
    if int(tmpJson['ret']) == 0:
        return True

    return tmpJson['msg']


# 拼装 params
def addParams(aApiName, aContent):
    # 签名
    signature = hashlib.sha1(USER + UKEY + STIME).hexdigest()
    # 拼装
    params = {
        'user': USER,
        'sig': signature,
        'stime': STIME,
        'apiname': aApiName,  # 固定值,不需要修改
        'sn': SN,
        'content': aContent,
        'times': '1'
    }
    return params


# 发送 请求
def requestUrl(params):
    try:
        encodedata = urllib.urlencode(params)
        request = urllib2.Request(url=URL, data=encodedata)
        response = urllib2.urlopen(request, timeout=30)
        recv_data = response.read()
        recv_data = recv_data.decode('raw_unicode_escape')
        return recv_data
    except Exception as e:
        print "Failed to reach the feie server"
    return None


if __name__ == '__main__':
    # print printOrder('打印')
    pass
